<template>
    <div id="home"> 
          <div v-if="!showLoading">
             <Header />
             <!-- 轮播图 -->
             <Sowing :sowing_list="sowing_list"/>
             <!-- 中部导航 -->
             <Nav :Nav_list="Nav_list"/>
             <!--  销售方式分类 -->
            <Tab :Tab_list="Tab_list"/>
           <!--  返回顶部 -->
            <MarkPage v-if="showBackStatus" :scrollToTop="scrollToTop"/>
          </div>
          <van-loading
                v-else
                type="spinner" 
                color="#75a342" 
                style="position:absolute;left: 50%;top: 40%;transform:translate(-50%)"
            >
               正在努力加载中....
         </van-loading> 
    </div>
</template>
<script>
    //1.引入
    import { getHomeData,getVegetables} from './../../service/api/index.js'  //拿到index.js 里面的getHomeData方法

   //2.引入组件
    import Header from './components/header/Header'
    import Sowing from './components/sowing/Sowing'
    import Nav from './components/nav/Nav'
    import Tab from './components/tab/Tab'
    import MarkPage from './components/markPage/MarkPage'



    //3.引入处理返回顶部的函数
    import {showBack,animate} from "@/config/global"

    //4.引入通知插件
    import PubSub from 'pubsub-js'
    import { Toast } from 'vant';

    //5.引入vuex
    import  {mapMutations,mapState} from 'vuex'

   //6.引入购物车的接口
    import {addGoodsToCart} from './../../service/api/index'

     export default {
        name:"Home",

         data(){
           return{
              //首页轮播图数据
              sowing_list:[],
              
              //导航品种分类数据
               Nav_list:[],

              //销量类型分类数据
               Tab_list:[],

              //是否显示加载图标
              showLoading:true,
              //是否显示返回顶部的按钮
              showBackStatus:false

           }
         },

        created(){
           //2.请求网络数据   调用getHomeData返回promise对象，然后可以调用promise的then方法，返回请求到的数据(response.data)
                 
                  getVegetables().then((response)=>{
                  // console.log(response);
                  if (response.success) {
                       //导航分类数据
                       this.Nav_list = response.data.pzleixing_list;
                       // console.log(this.Nav_list);
                       //销售方式分类数据
                      this.Tab_list = response.data.xlleixing_list;
                      //console.log(this.Tab_list);
                    

                     //隐藏加载动画
                     this.showLoading = false;
                     //开始监听滚动,到达一定位置显示返回顶部按钮
                     showBack((status)=>{
                       this.showBackStatus = status;
                     });
                  }
             }).catch(error=>{
                   // todo......
                   console.log(error);
             }),   //---catch


                  
                  getHomeData().then((response)=>{
                  //  console.log(response);
                     if (response.success) {
                             this.sowing_list = response.data.list[0].icon_list;
                             //隐藏加载动画
                             this.showLoading = false;
                             //开始监听滚动,到达一定位置显示返回顶部按钮
                             showBack((status)=>{
                               this.showBackStatus = status;
                             });     
                        }    //----if
                     }).catch(error=>{
                       // todo......
                      console.log(error);
                       })    //----catch



             },// ----created


                 
        
        computed:{
           ...mapState(["userInfo"])
        },
        mounted(){
         //订阅消息，(添加到购物车的消息)
           PubSub.subscribe('homeAddToCart',(msg,goods)=>{

                  if (msg ==='homeAddToCart') {
                       //判断用户是否登录
                      if (this.userInfo.token) {  //已经登录
                          this.dealGoodsAdd(goods)
                       }else{  //没有登录
                           this.$router.push('/login');
                       }
                  }
           })
        },

        components:{
          Header,
          Sowing,
          Nav,
          Tab,
          MarkPage
        },

        methods:{
          ...mapMutations(["ADD_GOODS"]),  //拿到mutations.js  里面的ADD_GOODS方法,记得先导入      import  {mapMutations}  from 'vuex'
          
            //1. 滚回顶部
           scrollToTop(){
            //做缓动动画返回顶部
              let docB = document.documentElement||document.body;
                animate(docB,{scrollTop:'0'},400,'ease-out');
           },

           //2.添加商品到购物车
           async dealGoodsAdd(goods){
            //2.1 调用服务器端的接口
              //调用addGoodsToCart将商品信息同步到服务器端 
              let result = await addGoodsToCart(goods.id,goods.name,goods.price,goods.small_image);
              console.log(result);
              // 因为这里同步到服务器端失败，所以直接保存在本地session的shopCart 里面
              if (result.status===500) {
                  this.ADD_GOODS({  
                      goodsId:goods.id,
                      goodsName:goods.name,
                      smallImage:goods.small_image,
                      goodsPrice:goods.price
                     });
                      //提示用户
                        Toast({ 
                          message:'添加到购物车成功',
                               duration:800
                        });
              }

           }

        },
       //哪里订阅就在哪里加取消操作
       beforeDestory(){
           //在发布和订阅都要销毁(这里是订阅的，要销毁)
            PubSub.unsubscribe('homeAddToCart');
       }
    }


</script>
<style lang="less" scoped>
   #home{
     width:100%;
     background-color:#f5f5f5;
     margin-bottom: 50px;
   }
</style>